<template>
  <div>
      <el-table :data="tableData" style="width: 100%" height="500" border>
            <el-table-column
                prop="id"
                label="菜品编号"
                width="180" header-align="center">
            </el-table-column>
            <el-table-column
                prop="name"
                label="菜品名称"
                width="180" header-align="center">
            </el-table-column>
            <el-table-column
                prop="price" width="180"
                label="菜品价格" header-align="center">
            </el-table-column>
            <el-table-column
                prop="add" width="180"
                label="购买" header-align="center">
                <template #default="scope">
                    <el-button type="primary" @click="add(scope.row.name)"
                    around>购买</el-button>                   
                </template>
            </el-table-column>
        </el-table>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    data(){
        return {
            num:null,
            tableData:[{id:1,name:'辣椒',price:'2'},{id:2,name:'鸡蛋',price:'1'},
            {id:3,name:'西红柿',price:'2'},{id:4,name:'大蒜',price:'1'},{id:5,name:'茄子',price:'5'},
            {id:6,name:'王老吉',price:'3'},{id:7,name:'牛肉',price:'20'},{id:8,name:'猪肉',price:'10'},]
        }
    },
    methods:{
        add(e){
            axios.get('http://127.0.0.1:3008/api/selectFood?name='+ e +'')
            .then(res=>{
                console.log(res.data);
                this.num = res.data
                //如果不存在，添加
                if(res.data.status){
                    console.log(111);
                    axios.get('http://127.0.0.1:3008/api/addFood?name='+ e +'')
                    .then(res=>{
                        console.log(res.data);
                        this.$message({
                            message:'增加成功',
                            duration:1000,
                            type: 'success',
                        }) 
                    })
                }
                //存在，更新
                else{
                    this.num += 10
                    axios.get('http://127.0.0.1:3008/api/updateFood?name='+ e +' &num='+ this.num +'')
                    .then(res=>{
                        console.log(res.data);
                        this.$message({
                            message:'增加成功',
                            duration:1000,
                            type: 'success',
                        })  
                    })
                }
            })
        }
    },
    
}
</script>

<style>
/* 让表格中内容元素居中 */
.el-table__body td .cell {
      text-align: center;
}
</style>